package com.base.helper;

import java.io.IOException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

import com.base.utils.Produce;
import lombok.extern.log4j.Log4j;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

@Log4j
public class ZJYCallHelper {
    //静态变量 count 用于线路切换
    static int count = 0;
    //对象锁，用于控制count变量的递增
    public static Object object =new Object();
    String url = "http://api.ytx.net";
    String accountSID = "9f938c4471484c1ba0d996718105e136";
    String authToken = "0483d02ae0604288bd0d61808e3230df";
    String version = "201512";
    String func = "call";
    String funcURL = "DailbackCall.wx";
    String action = "callDailBack";
    String appid = "5f7720f346924ea49e5626ec9f63105d";
    String passthroughCall1 = "08386724689";
    List<String> passthroughCallList = new LinkedList<String>() {
        {
            add("08386724689");
            add("08386724632");
            add("08386724697");
            add("08386724626");
            add("08386724656");
            add("08386724526");
            add("08386724660");
            add("08386724650");
            add("08386724616");
            add("08386724670");
            add("08386724644");
            add("08386724534");
            add("08386724553");
            add("08386724639");
            add("08386724530");
            add("08386724643");
            add("08386724538");
            add("08386724668");
            add("08386724543");
            add("08386724603");
        }
    };
    String customParm = "";   //订单ID

    public ZJYCallHelper() {
    }

    public String requestPhoneUrl(String dateStr) {
        String sign = this.accountSID + this.authToken + dateStr;
        sign = MD5(sign);
        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append(this.url);
        strBuffer.append("/").append(this.version);
        strBuffer.append("/sid/").append(this.accountSID);
        strBuffer.append("/").append(this.func);
        strBuffer.append("/").append(this.funcURL);
        strBuffer.append("?Sign=").append(sign.toLowerCase());
        return strBuffer.toString();
    }

    public JSONObject requestHeader(String dateStr) {
        String accept = "application/json";
        String contentType = "application/json;charset=utf-8";
        String authorization = this.accountSID + "|" + dateStr;
        authorization = Base64.encodeBase64String(authorization.getBytes()).replaceAll("\\r|\\n", "");
        Map<String, String> headerMap = new HashMap();
        headerMap.put("Authorization", authorization);
        headerMap.put("Accept", accept);
        headerMap.put("Content-Type", contentType);
        JSONObject headerJson = JSONObject.fromObject(headerMap);
        return headerJson;
    }

    public JSONObject requestParam(String src, String dst, String credit, String customParm) {
        Long TimeStamp = System.currentTimeMillis();
//        BigDecimal time1=new BigDecimal(TimeStamp);
//        Integer time=time1.intValue();
        int j = 0;
        //通过Synchrized 锁
        synchronized (object) {
            j = count % 20;
            count++;
        }

        log.warn("当前线路:" + j);
        log.warn("当前的cout数目:" + count);

        Map<String, String> map = new HashMap();
        map.put("action", this.action);
        map.put("appid", this.appid);
        map.put("src", src);
        map.put("dst", dst);
        map.put("credit", credit);
        map.put("srcclid", passthroughCallList.get(j));
        map.put("dstclid", passthroughCallList.get(j));
//        map.put("srcclid",passthroughCall1);
//        map.put("dstclid",passthroughCall1);
        map.put("customParm", customParm);
        JSONObject jsonParam = JSONObject.fromObject(map);
        return jsonParam;
    }

    public static JSONObject httpPhone(String srcMobile, String dstMobile, String credit, String orderId) {
        SimpleDateFormat dateFormart = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = dateFormart.format(new Date());
        ZJYCallHelper phoneUtil = new ZJYCallHelper();
        String url = phoneUtil.requestPhoneUrl(dateStr);
        JSONObject headerJson = phoneUtil.requestHeader(dateStr);
        JSONObject jsonParam = phoneUtil.requestParam(srcMobile, dstMobile, credit, orderId);
        JSONObject resultJson = httpPostByPhone(url, headerJson, jsonParam, false);
        log.warn(resultJson.get("statusCode") + "========" + resultJson.get("statusMsg"));
        return resultJson;
    }

    public static void main(String[] args) {
        String srcMobile = "18055603791";
        String dstMobile = "18557542013";
        String credit = "1800";
        String orderId = Produce.getUUID();
        JSONObject resultJson = httpPhone(srcMobile, dstMobile, credit, orderId);
        System.out.println(resultJson.get("statusCode") + "========" + resultJson.get("statusMsg"));
    }

    public static final String MD5(String s) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;

            for (int i = 0; i < j; ++i) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            return new String(str);
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
    }

    public static JSONObject httpPostByPhone(String url, JSONObject headerParam, JSONObject jsonParam, boolean noNeedResponse) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);

        try {
            if (headerParam != null) {
                Map<String, String> headMap = (Map) JSONObject.toBean(headerParam, Map.class);
                Iterator var9 = headMap.entrySet().iterator();

                while (var9.hasNext()) {
                    Entry<String, String> entry = (Entry) var9.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                        method.setHeader(key, value);
                    }
                }
            }

            if (jsonParam != null) {
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }

            HttpResponse result = httpClient.execute(method);
            System.out.println(result.getStatusLine().getStatusCode());
            url = URLDecoder.decode(url, "UTF-8");
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";

                try {
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }

                    jsonResult = JSONObject.fromObject(str);
                } catch (Exception var12) {
                    System.out.println("post请求提交失败:" + var12);
                }
            }
        } catch (IOException var13) {
            System.out.println("post请求提交失败:" + var13);
        }

        return jsonResult;
    }
}
